package com.shsoft.component;

import com.shsoft.util.FileUtil;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;


public class ImageComponent extends BaseComponent{

    private int width;

    private int height;

    private String imagePath;

    private String imageName;

    private boolean stretch;

    private transient Image image;

    @Override
    public void drawComponent(GraphicsContext gc) {
        if(image != null){
            if(stretch){
                gc.drawImage(image,getX(),getY(),width,height);
            }else {
                gc.drawImage(image,0,0,width,height,getX(),getY(),width,height);
            }
        }
    }

    @Override
    public void drawComponentBorder(Canvas canvas) {
        if(!StringUtils.isEmpty(imagePath)){
            GraphicsContext gc = canvas.getGraphicsContext2D();
            gc.setStroke(Color.GREY);
            gc.strokeRect(getX(), getY(), width, height);
        }
    }

    @Override
    public boolean isMe(double x, double y) {
        if(x >= getX() && x <= getX() + width && y >= getY() && y <= getY() + height){
            return true;
        }
        return false;
    }

    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
        ois.defaultReadObject();
        String templateName = imagePath.substring(imagePath.indexOf("template\\") + 9, imagePath.indexOf("\\images"));
        File file = new File(FileUtil.getImagePath(templateName, imageName));
        if(file.exists()){
            image = new Image(file.toURI().toString());
        }
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }

    public boolean isStretch() {
        return stretch;
    }

    public void setStretch(boolean stretch) {
        this.stretch = stretch;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

}
